package com.lzugis.line;

import com.vividsolutions.jts.geom.*;
import com.vividsolutions.jts.io.WKTReader;
import org.geotools.data.FeatureWriter;
import org.geotools.data.Transaction;
import org.geotools.data.shapefile.ShapefileDataStore;
import org.geotools.data.shapefile.ShapefileDataStoreFactory;
import org.geotools.feature.simple.SimpleFeatureTypeBuilder;
import org.geotools.referencing.crs.DefaultGeographicCRS;
import org.opengis.feature.simple.SimpleFeature;
import org.opengis.feature.simple.SimpleFeatureType;

import java.io.File;
import java.io.Serializable;
import java.nio.charset.Charset;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.HashMap;
import java.util.Map;

public class Point2Line {
    // db相关
    private static Connection c = null;
    // shp相关
    private static String rootPath = "D:/project/year2021/hebei/data/";
    private static ShapefileDataStore ds = null;
    private static FeatureWriter<SimpleFeatureType, SimpleFeature> writer = null;

    // 获取数据库连接
    public void getC() {
        try {
            Class.forName("org.postgresql.Driver");
            String url = "jdbc:postgresql://localhost:5432/lzugis";
            c = DriverManager.getConnection(url, "postgres", "root");
            c.setAutoCommit(false);
            System.out.println("Opened database successfully");
        } catch ( Exception e ) {
            System.err.println( e.getClass().getName()+": "+ e.getMessage() );
            System.exit(0);
        }
    }

    /**
     * 初始化
     * 1.连接数据库
     * 2.
     */
    public void init() {
        this.getC();
        this.createShp();
    }

    // 初始化创建shp
    public void createShp() {
        try {
            //创建shape文件对象
            String shppath = rootPath + "segments.shp";
            System.out.println(shppath);
            File file = new File(shppath);
            Map<String, Serializable> params = new HashMap<String, Serializable>();
            params.put(ShapefileDataStoreFactory.URLP.key, file.toURI().toURL());
            ds = (ShapefileDataStore) new ShapefileDataStoreFactory().createNewDataStore(params);
            //定义图形信息和属性信息
            SimpleFeatureTypeBuilder tb = new SimpleFeatureTypeBuilder();
            tb.setCRS(DefaultGeographicCRS.WGS84);
            tb.setName("shapefile");
            tb.add("the_geom", LineString.class);
            tb.add("line_name", String.class);
            tb.add("tower_num", String.class);
            tb.add("startx", Float.class);
            tb.add("starty", Float.class);
            tb.add("endx", Float.class);
            tb.add("endy", Float.class);
            ds.createSchema(tb.buildFeatureType());
            //设置编码
            Charset charset = Charset.forName("GBK");
            ds.setCharset(charset);
            //设置Writer
            writer = ds.getFeatureWriter(ds.getTypeNames()[0], Transaction.AUTO_COMMIT);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        try {
            long start = System.currentTimeMillis();
            Point2Line p2l = new Point2Line();
            p2l.init();
            String sqlNames = "SELECT DISTINCT line_name FROM hebei_tower";
            Statement stmtName = c.createStatement();
            ResultSet names = stmtName.executeQuery(sqlNames);
            WKTReader wktReader = new WKTReader();
            while (names.next()) {
                String lineName = names.getString("line_name");
                String sqlTowers = "SELECT lon, lat, tower_number FROM hebei_tower where line_name='" + lineName + "' ORDER BY order_num";
                Statement stmtTowers = c.createStatement();
                ResultSet towers = stmtTowers.executeQuery(sqlTowers);
                towers.next();
                float lonS = towers.getFloat("lon");
                float latS = towers.getFloat("lat");
                String towerNum = towers.getString("tower_number");
                while (towers.next()) {
                    float lonE = towers.getFloat("lon");
                    float latE = towers.getFloat("lat");
                    //写下一条
                    SimpleFeature feature = null;
                    feature = writer.next();
                    feature.setAttribute("line_name", lineName);
                    feature.setAttribute("startx", lonS);
                    feature.setAttribute("starty", latS);
                    feature.setAttribute("endx", lonE);
                    feature.setAttribute("endy", latE);
                    feature.setAttribute("tower_num", towerNum);
                    StringBuffer wkt = new StringBuffer();
                    wkt.append("LINESTRING(");
                    wkt.append(lonS + " " + latS);
                    wkt.append("," + lonE + " " + latE);
                    wkt.append(")");
                    Geometry geom = wktReader.read(wkt.toString());
                    feature.setAttribute("the_geom", geom);
                    lonS = lonE;
                    latS = latE;
                    towerNum = towers.getString("tower_number");
                }
                towers.close();
                stmtTowers.close();
            }
            // 停止写入
            writer.write();
            writer.close();
            ds.dispose();
            names.close();
            // 关闭数据库
            stmtName.close();
            c.close();
            System.out.println("共耗时" + (System.currentTimeMillis() - start) + "ms");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
